<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\Models\Auth\Role;
use App\Models\Auth\User;
use App\Models\Auth\UserParkingLot;
use App\Models\Auth\UserRelation;
use App\Models\Common\ApiResponse;
use App\Models\Common\BaseModel;
use App\Models\Merchant\MerchantUser;
use App\Models\ParkingLot\ParkingLot;
use Illuminate\Http\Request;
use Illuminate\Support\Arr;
use Illuminate\Support\Str;
use Illuminate\Database\Eloquent\Builder;

class UserController extends Controller
{

    public $name = '用户管理';

    public function index(Request $request)
    {
        $user = admin();
        $more = $request->post();

        $baseQuery = User::with(['parkingLots', 'roles', 'merchant']);

        $page = intval($request->get('page') ?: 1);
        $perPage = intval($request->get('per_page') ?: 10);

//        switch ($user->identity) {
//            case User::IDENTITY_SYSTEM:
//                if (sourceParkingLot()) {
//                    $baseQuery->whereHasIn('parkingLots', function ($childQuery) {
//                        $childQuery->where('id', getParkingLotID());
//                    });
//                    $baseQuery->where('identity', User::IDENTITY_PARKING_LOT);
//                } else {
//                    $baseQuery->whereIn('identity', [User::IDENTITY_PARKING_LOT, User::IDENTITY_SYSTEM]);
//                }
//                break;
//            case User::IDENTITY_AGENT:
//                if (sourceParkingLot()) {
//                    $baseQuery->whereHasIn('parkingLots', function ($childQuery) {
//                        $childQuery->where('id', getParkingLotID());
//                    });
//                    $baseQuery->where('identity', User::IDENTITY_PARKING_LOT);
//                } else {
//                    $baseQuery->where('identity', [User::IDENTITY_PARKING_LOT, User::IDENTITY_AGENT]);
//                }
//                break;
//            case User::IDENTITY_STATION:
//            case User::IDENTITY_PARKING_LOT:
//                $baseQuery->whereHasIn('parkingLots', function ($childQuery) {
//                    $childQuery->where('id', getParkingLotID());
//                });
//
//                $baseQuery->where('identity', $user->identity);
//                break;
//            case User::IDENTITY_MERCHANT:
//                $merchantID = getMerchantID();
//                $userIDs = MerchantUser::where('merchant_id', $merchantID)->pluck('user_id');
//                $baseQuery->whereIn('id', $userIDs);
//                $baseQuery->where('identity', $user->identity);
//                break;
//            default:
//                throw new \InvalidArgumentException('无查看用户列表的权限');
//        }
//        if (!$user->super) {
//            $baseQuery->where(function ($childQuery) use ($user) {
//                if ($systemAdmin = User::query()->where('identity', $user->identity)->where('super', true)->first()) {
//                    $childQuery->where('id', '<>', $systemAdmin->id);
//                }
//            });
//        }

        // 显示所有子孙账号
        if (!$user->isSystemSuper) {
            $baseQuery->whereIn('id', $user->childIDs);
        }

        self::searchQuery($baseQuery, $more);

//        $paginationDat = $baseQuery->paginate(intval($request->get('per_page')), '*', 'page', intval($request->get('page')));
        $users = BaseModel::getList($baseQuery, $page, $perPage);

        return ApiResponse::return('', $users);
    }

    private function searchQuery(Builder $query, array $input = [])
    {
        $name = Arr::get($input, 'name');
        if (null !== $name) {
            $query->where('name', 'like', '%'.$name.'%');
        }

        if ($username = Arr::get($input, 'username')) {
            $query->where('username', 'like', '%'.$username.'%');
        }

    }

    public function store(Request $request)
    {
        $this->admin = $admin = admin();
        $bindToRoles = $adminParkingLotIDs = [];
        $adminMerchantID = '';
        $this->logContent = '编辑用户';
        $identity = $request->get('identity');
        $isSystemSuper = false;

        if ($uid = $request->get('id')) {
            $user = User::query()->findOrFail($uid);
            $isSystemSuper = $user->isSystemSuper;
            $identity = $user->identity; // 身份不可修改
        } else {
            $this->logContent = '新增用户';
            $user = new User;
            $user->id = Str::orderedUuid()->toString();
        }

        if (!in_array($identity, array_keys(User::IDENTITIES))) {
            throw new \InvalidArgumentException('身份类型错误');
        }

        switch ($admin->identity) {
            case User::IDENTITY_SYSTEM:
                if ($identity === User::IDENTITY_PARKING_LOT) {
                    $parkingLotIDs = $request->get('parking_lot_ids');
                    $parkingLotIDs = array_unique(array_filter(explode(',', $parkingLotIDs)));
                    !$uid && $user->super = true;
                } elseif ($identity === User::IDENTITY_SYSTEM) {
//                    $parkingLotIDs = [];
                    $parkingLotIDs = $request->get('parking_lot_ids');
                    $parkingLotIDs = array_unique(array_filter(explode(',', $parkingLotIDs)));
                    !$uid && $user->super = false;
                } else {
                    throw new \InvalidArgumentException('仅可创建系统管理和车场管理身份的账号');
                }
                break;
            case User::IDENTITY_AGENT:
                if ($identity === User::IDENTITY_SYSTEM) {
//                    throw new \InvalidArgumentException('不可创建系统管理员身份的账号');
                    $identity = User::IDENTITY_AGENT;
                }
                !$uid && $user->super = false;
                if (sourceParkingLot()) {
                    $parkingLotIDs[] = getParkingLotID();
                    $this->parkingLotID = getParkingLotID();
                } else {
                    if ($identity === User::IDENTITY_PARKING_LOT) {
                        $parkingLotIDs = $request->get('parking_lot_ids');
                        $parkingLotIDs = array_unique(array_filter(explode(',', $parkingLotIDs)));
                        !$uid && $user->super = true;
                    } elseif ($identity === User::IDENTITY_AGENT) {
//                        $parkingLotIDs = [];
                        $parkingLotIDs = $request->get('parking_lot_ids');
                        $parkingLotIDs = array_unique(array_filter(explode(',', $parkingLotIDs)));
                    }else {
                        throw new \InvalidArgumentException('仅可创建运营商员工身份的账号');
                    }
                }
                break;
            case User::IDENTITY_PARKING_LOT:
                if ($identity === User::IDENTITY_SYSTEM) {
                    throw new \InvalidArgumentException('车场内不可创建系统管理员身份的账号');
                }
                $identity = User::IDENTITY_PARKING_LOT;

                $parkingLotIDs = $request->get('parking_lot_ids');
                $parkingLotIDs = array_unique(array_filter(explode(',', $parkingLotIDs)));
                if (array_diff($parkingLotIDs, $admin->getParkingLotIdsAttribute())) {
                    throw new \InvalidArgumentException('不可选择无管理权限的车场');
                }

//                $parkingLotIDs[] = getParkingLotID();
//                $this->parkingLotID = getParkingLotID();
                !$uid && $user->super = false;

                if ($parkingLotIDs) {
                    $this->parkingLotID = $parkingLotIDs[0];
                }
                break;
            case User::IDENTITY_MERCHANT:
                $identity = User::IDENTITY_MERCHANT;
                $parkingLotIDs[] = getParkingLotID();
                $this->parkingLotID = getParkingLotID();
                $adminMerchantID = getMerchantID();
                !$uid && $user->super = false;
                break;
            case User::IDENTITY_STATION:
            default:
            throw new \InvalidArgumentException('当前账号身份不可编辑或创建账号');
        }

        $user->identity = $identity;
        $user->fill($request->only('username', 'name', 'contact', 'banned'));

        if (!$user->name) {
            throw new \InvalidArgumentException('账号昵称不得为空');
        }

        if (!$user->username) {
            throw new \InvalidArgumentException('账号登录名不得为空');
        }

        if (User::where('username', $user->username)->where('id', '<>', $user->id)->exists()) {
            throw new \InvalidArgumentException('账号登录名已被其他账号占用');
        }

        if ($password = $request->get('password')) {
            $user->password = bcrypt($password);
        }

        if (!$user->password) {
            throw new \InvalidArgumentException('账号登录密码不得为空');
        }

        $user->contact = strval($user->contact);

        if ($parkingLotIDs) {
            $parkingLots = ParkingLot::findMany($parkingLotIDs);
            if (!$parkingLots->count() || count($parkingLotIDs) !== $parkingLots->count()) {
                throw new \InvalidArgumentException('被操作账号关联的车场ID未找到匹配的数据');
            }

            foreach ($parkingLotIDs as $parkingLotID) {
                $adminParkingLotIDs[] = ['user_id' => $user->id, 'parking_lot_id' => $parkingLotID];
            }
        }

        if (!$user->super && $roleIDs = $request->get('role_ids')) {
            $roleIDs = array_unique(array_filter(explode(',', $roleIDs)));

            if ($user->identity === User::IDENTITY_MERCHANT) {
                $bindToRoles = Role::where('merchant_id', $adminMerchantID)->findMany($roleIDs)->pluck('name')->toArray();
            }
            else {
//                if ($user->identity === User::IDENTITY_SYSTEM || $user->identity === User::IDENTITY_AGENT) {
//                    $bindToRoles = Role::where('parking_lot_id', '')->findMany($roleIDs)->pluck('name')->toArray();
//                } else {
//                    $bindToRoles = Role::whereIn('parking_lot_id', $parkingLotIDs)->findMany($roleIDs)->pluck('name')->toArray();
//                }
                $bindToRoles = Role::findMany($roleIDs)->pluck('name')->toArray();
            }

            if (!$bindToRoles) {
                throw new \InvalidArgumentException('关联的角色ID未找到匹配的数据');
            }
        }

        if ($isSystemSuper) {
            if ($admin->id !== $user->id) {
                throw new \InvalidArgumentException('超级管理员不可编辑');
            }

            if ($user->identity !== User::IDENTITY_SYSTEM) {
                throw new \InvalidArgumentException('超级管理员身份不可修改');
            }
        }

        // 新增子账号level加一
        $userRelations = [];
        if (!$uid) { // (!$user->super || User::IDENTITY_AGENT === $admin->identity)
            if (!$admin->isSystemSuper) {
                $user->level = $user->super ? 0 : $admin->level + 1;
                $userRelations[] = [
                    'user_id' => $admin->id,
                    'child_id' => $user->id
                ];
                UserRelation::where('child_id', $admin->id)->get()->each(function ($relation) use (&$userRelations, $user) {
                    $userRelations[] = [
                        'user_id' => $relation->user_id,
                        'child_id' => $user->id
                    ];
                });
            }
        }

        if ($request->exists('remark')) {
            $user->remark = $request->get('remark') ?: '';
        }

        if ($user = \DB::transaction(function () use ($user, $adminParkingLotIDs, $bindToRoles, $adminMerchantID, $userRelations) {

            $user->save();
            UserParkingLot::where('user_id', $user->id)->delete();
            $adminParkingLotIDs && UserParkingLot::insertOrIgnore($adminParkingLotIDs);
            $adminMerchantID && MerchantUser::insertOrIgnore([
                'user_id' => $user->id,
                'merchant_id' => $adminMerchantID
            ]);
            $user->syncRoles($bindToRoles);
            $userRelations && UserRelation::insertOrIgnore($userRelations);
            return $user->refresh();
        })) {
            return ApiResponse::return('', $user->id);
        }
        return ApiResponse::return('', '', ApiResponse::RESP_CODE_FAILURE);
    }

    public function show($id)
    {
        $user = admin();
        $admin = User::with(['parkingLots', 'roles'])->findOrFail($id);

        if ($admin->isSystemSuper && $user->id !== $admin->id) {
            throw new \InvalidArgumentException('无权查看超级管理员的信息');
        }

        return ApiResponse::return('', $admin->reassignPermissions());
    }

    public function info(Request $request)
    {
        if (!$user = admin()) {
            throw new \InvalidArgumentException('获取当前账号登录状态失败');
        }
        $this->needLogging = false;
        $admin = User::with(['parkingLots', 'roles', 'merchant'])->findOrFail($user->id);
        $admin->parking_lot_id = $admin->getParkingLotIdAttribute();
        return ApiResponse::return('', $admin->reassignPermissions());
    }

    public function destroy($id)
    {
        $this->admin = $user = admin();
        $this->logContent = '删除用户';
        $this->parkingLotID = getParkingLotID(false, true);

        if (!$needDelAdmin = User::find($id)) {
            return ApiResponse::return();
        }

        if ($needDelAdmin->isSystemSuper) {
            return ApiResponse::fail('超级管理员不得删除');
        }

        if ($needDelAdmin->super) {
            if ($needDelAdmin->identity === User::IDENTITY_AGENT) {
                return ApiResponse::fail('运营商管理员账号不可删除');
            }

            if ($needDelAdmin->identity === User::IDENTITY_MERCHANT) {
                return ApiResponse::fail('商户管理员账号不可删除');
            }
        }

        if (\DB::transaction(function () use ($id) {
            UserParkingLot::where('user_id', $id)->delete();
            MerchantUser::where('user_id', $id)->delete();
            User::where('id', $id)->delete();
            UserRelation::where('user_id', $id)->delete();
            UserRelation::where('child_id', $id)->delete();
            \DB::table('model_has_roles')->where('model_id', $id)->delete();
            return true;
        })) {
            return ApiResponse::return();
        }

        return ApiResponse::return('', '', ApiResponse::RESP_CODE_FAILURE);
    }
}
